<?php

declare(strict_types=1);

namespace Plugin\Attractions\AttractionManagement\Repository;

use App\Repository\IRepository;
use Hyperf\Collection\Arr;
use Hyperf\Collection\Collection;
use Hyperf\Database\Model\Builder;
use Plugin\Attractions\AttractionManagement\Model\AttractionType;

class AttractionTypeRepository extends IRepository
{
    public function __construct(protected readonly AttractionType $model) {}

    public function handleSearch(Builder $query, array $params): Builder
    {
        return $query
            ->when(Arr::get($params, 'id'), static function (Builder $query, $id) {
                $query->whereIn('id', Arr::wrap($id));
            })
            ->when(Arr::get($params, 'name'), static function (Builder $query, $name) {
                $query->where('name', 'like', '%' . $name . '%');
            })
            ->when(Arr::get($params, 'sort'), static function (Builder $query, $sort) {
                $query->orderBy('sort', $sort == 1 ? 'asc' : 'desc');
            })
            ->when(Arr::get($params, 'parentId'), static function (Builder $query, $parent_id) {
                $query->where('parent_id', $parent_id);
            })
            ->when(Arr::get($params, 'level'), static function (Builder $query, $level) {
                $query->where('level', $level);
            })
            ->when(Arr::get($params, 'type'), static function (Builder $query, $type) {
                $query->where('type', $type);
            });
    }

    public function list(array $params = []): Collection
    {
        return $this->perQuery($this->getQuery(), $params)
            ->with(['parent'])
            ->get(['id', 'type', 'name', 'description', 'sort', 'parent_id', 'level']);
    }

    public function isValidType(int $id): bool
    {
        return $this->existsById($id);
    }
}